<template>
  <div class="booking-manage-container">
    <el-card class="booking-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              style="width: 184px"
              v-model="searchForm.keyword"
              placeholder="预约单号/客户姓名/手机号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="摄影师">
            <el-select
              style="width: 120px"
              v-model="searchForm.photographerId"
              placeholder="选择摄影师"
              clearable
            >
              <el-option
                v-for="item in photographerOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="拍摄类型">
            <el-select v-model="searchForm.shootingType" placeholder="选择类型" clearable>
              <el-option label="婚纱摄影" value="wedding" />
              <el-option label="写真" value="portrait" />
              <el-option label="儿童摄影" value="children" />
              <el-option label="全家福" value="family" />
              <el-option label="孕妇照" value="maternity" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="状态">
            <el-select
              style="width: 100px"
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option label="待确认" value="1" />
              <el-option label="已确认" value="2" />
              <el-option label="已完成" value="3" />
              <el-option label="已取消" value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="预约时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 预约列表 -->
      <el-table v-loading="loading" :data="bookingList" style="width: 100%" border>
        <el-table-column prop="booking_number" label="预约单号" width="180" />

        <el-table-column label="客户信息" min-width="180">
          <template #default="{ row }">
            <div class="customer-info">
              <div>{{ row.customer_name }}</div>
              <div class="phone">{{ row.customer_phone }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="摄影师" width="120">
          <template #default="{ row }">
            {{ row.photographer.nickname }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="拍摄类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getShootingTypeTagType(row.shootingType)">
              {{ getShootingTypeLabel(row.shootingType) }}
            </el-tag>
          </template>
        </el-table-column> -->

        <el-table-column prop="shooting_date" label="拍摄时间" width="180" />

        <el-table-column label="价格信息" width="180">
          <template #default="{ row }">
            <div class="price-info">
              <div>总价：¥{{ row.total_amount }}</div>
              <div>定金：¥{{ row.deposit_amount }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button class="detail-btn" type="primary" link @click="handleViewDetail(row)">
              查看详情
            </el-button>
            <el-button
              class="confirm-btn"
              v-if="
                row.status.toString() === '1' &&
                currentUserId === row.photographer_id &&
                userRole === 'photographer'
              "
              type="success"
              link
              @click="handleConfirm(row)"
            >
              确认预约
            </el-button>
            <el-button
              class="cancel-btn"
              v-if="['1', '2'].includes(row.status.toString())"
              type="danger"
              link
              @click="handleCancel(row)"
            >
              取消预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="预约详情" width="600px">
        <div class="booking-detail" v-if="currentBooking">
          <div class="detail-item">
            <span class="label">预约单号：</span>
            <span>{{ currentBooking.booking_number }}</span>
          </div>
          <div class="detail-item">
            <span class="label">客户姓名：</span>
            <span>{{ currentBooking.customer_name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span>{{ currentBooking.customer_phone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">摄影师：</span>
            <span>{{ currentBooking.photographer.nickname }}</span>
          </div>
          <!-- <div class="detail-item">
            <span class="label">拍摄类型：</span>
            <span>{{ getShootingTypeLabel(currentBooking.shootingType) }}</span>
          </div> -->
          <div class="detail-item">
            <span class="label">拍摄时间：</span>
            <span>{{ currentBooking.shooting_date }}</span>
          </div>
          <div class="detail-item">
            <span class="label">套餐：</span>
            <span>{{ currentBooking.package.name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">总价：</span>
            <span>¥{{ currentBooking.total_amount }}</span>
          </div>
          <div class="detail-item">
            <span class="label">定金：</span>
            <span>¥{{ currentBooking.deposit_amount }}</span>
          </div>
          <div class="detail-item">
            <span class="label">状态：</span>
            <el-tag :type="getStatusTagType(currentBooking.status)">
              {{ getStatusLabel(currentBooking.status) }}
            </el-tag>
          </div>
          <div class="detail-item" v-if="currentBooking.remark">
            <span class="label">备注：</span>
            <span>{{ currentBooking.remark }}</span>
          </div>
          <div class="detail-item" v-if="currentBooking.cancel_reason">
            <span class="label">取消原因：</span>
            <span>{{ currentBooking.cancel_reason }}</span>
          </div>
        </div>
      </el-dialog>

      <!-- 取消预约对话框 -->
      <el-dialog v-model="cancelDialogVisible" title="取消预约" width="500px">
        <el-form :model="cancelForm">
          <el-form-item label="取消原因" :rules="[{ required: true, message: '请输入取消原因' }]">
            <el-input
              v-model="cancelForm.reason"
              type="textarea"
              rows="3"
              placeholder="请输入取消原因"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCancel">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Booking, BookingQuery, ShootingType, BookingStatus } from '@/types/booking'
import { cancelBooking, confirmBooking, getBookings } from '@/api/booking'
import { getPhotographersList } from '@/api/photographer' // 导入获取摄影师列表的API
import type { Photographer } from '@/types/photographer' // 导入摄影师类型
import { useUserStore } from '@/stores/user'
import { getUserInfo } from '@/api/user'
import { useRouter } from 'vue-router'

// 添加用户信息相关的变量
const userStore = useUserStore()
const userRole = computed(() => userStore.userRole)
const currentUserId = computed(() => userStore.userDetail?.id)

// 摄影师选项
const photographerOptions = ref<Photographer[]>([])

// 搜索表单
const searchForm = reactive<BookingQuery>({
  keyword: '',
  status: undefined,
  startTime: undefined,
  endTime: undefined,
  photographerId: undefined, // 添加摄影师ID字段
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)
const currentBooking = ref<Booking | null>(null)

// 预约列表数据
const bookingList = ref<Booking[]>([])

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  const types: Record<number, string> = {
    1: 'warning',
    2: 'success',
    3: 'info',
    4: 'danger',
  }
  return types[status]
}

// 获取状态标签文本
const getStatusLabel = (status: number) => {
  const labels: Record<number, string> = {
    1: '待确认',
    2: '已确认',
    3: '已完成',
    4: '已取消',
  }
  return labels[status]
}

// 处理日期范围变化
const handleDateRangeChange = (val: [string, string] | null) => {
  if (val) {
    searchForm.startTime = val[0]
    searchForm.endTime = val[1]
  } else {
    searchForm.startTime = undefined
    searchForm.endTime = undefined
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = undefined
  searchForm.startTime = undefined
  searchForm.endTime = undefined
  dateRange.value = null
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 查看详情
const router = useRouter()
const handleViewDetail = (row: Booking) => {
  router.push(`/booking/${row.id}`)
}

// 确认预约
const handleConfirm = async (row: Booking) => {
  try {
    await ElMessageBox.confirm('确定要接受这个预约吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await confirmBooking(row.id)
    ElMessage.success('预约已确认')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const cancelDialogVisible = ref(false)
const cancelForm = reactive({
  reason: '',
  bookingId: null as number | null,
})

// 修改取消预约的处理方法
const handleCancel = (row: Booking) => {
  cancelForm.bookingId = row.id
  cancelForm.reason = ''
  cancelDialogVisible.value = true
}

const submitCancel = async () => {
  if (!cancelForm.reason.trim()) {
    ElMessage.warning('请输入取消原因')
    return
  }

  try {
    await cancelBooking(cancelForm.bookingId!, cancelForm.reason)
    ElMessage.success('预约已取消')
    cancelDialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('取消预约失败')
  }
}

// 获取摄影师列表
/**
 * 获取摄影师列表用于筛选
 * 该函数从服务器获取所有摄影师信息，用于预约筛选
 */
const fetchPhotographers = async () => {
  try {
    const { data } = await getPhotographersList({
      pageSize: 100, // 获取足够多的摄影师数据用于筛选
    })
    photographerOptions.value = data.data.items
  } catch (error) {
    ElMessage.error('获取摄影师列表失败')
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getBookings({
      keyword: searchForm.keyword,
      status: searchForm.status ? Number(searchForm.status) : undefined,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
      photographerId: searchForm.photographerId, // 添加摄影师ID参数
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    bookingList.value = data.data.items
    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
    return []
  } finally {
    loading.value = false
  }
}

const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    userStore.updateUserDetails(data.data)
    fetchData()
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

onMounted(() => {
  fetchUserInfo()
  fetchPhotographers() // 在组件挂载时获取摄影师列表
})
</script>

<style scoped>
.booking-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.booking-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.customer-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.phone {
  color: #666;
  font-size: 13px;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.booking-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #666;
}
.detail-btn {
  margin-right: 12px;
}
.confirm-btn {
  margin-left: 0px;
  margin-right: 12px;
}
.cancel-btn {
  margin-left: 0px;
}
</style>
